//
//  QRCodeViewController.m
//  SelfDriving
//
//  Created by apple on 15/10/12.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "QRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "GroupDetails.h"
@interface QRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>
@property ( strong , nonatomic ) AVCaptureDevice * device;
@property ( strong , nonatomic ) AVCaptureDeviceInput * input;
@property ( strong , nonatomic ) AVCaptureMetadataOutput * output;
@property ( strong , nonatomic ) AVCaptureSession * session;
@property ( strong , nonatomic ) AVCaptureVideoPreviewLayer * preview;
@property (strong, nonatomic) UIImageView *scanLayer;

@end

@implementation QRCodeViewController{
    UIView *boxView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Device
    _device = [ AVCaptureDevice defaultDeviceWithMediaType : AVMediaTypeVideo ];
    // Input
    NSError *error = nil;
    _input = [ AVCaptureDeviceInput deviceInputWithDevice : self . device error : &error];
    // Output
    _output = [[ AVCaptureMetadataOutput alloc ] init ];
    [ _output setMetadataObjectsDelegate : self queue : dispatch_get_main_queue ()];
    // Session
    _session = [[ AVCaptureSession alloc ] init ];
    [ _session setSessionPreset : AVCaptureSessionPresetHigh ];
    if ([ _session canAddInput : self . input ])
    {
        [ _session addInput : self . input ];
    }
    if ([ _session canAddOutput : self . output ])
    {
        [ _session addOutput : self . output ];
    }
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"相机启动失败" message:@"请为乐津开放相机权限，手机设置->隐私->相机->一米->打开" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output . metadataObjectTypes = @[ AVMetadataObjectTypeQRCode ] ;
    //    [ _output setRectOfInterest : CGRectMake (( 124 )/ SCRE_HEIGHT ,(( SCRE_WIDTH - 220 )/ 2 )/ SCRE_WIDTH , 220 / SCRE_HEIGHT , 220 / SCRE_WIDTH )];
    // Preview
    _preview =[ AVCaptureVideoPreviewLayer layerWithSession : _session ];
    _preview . videoGravity = AVLayerVideoGravityResizeAspectFill ;
    _preview . frame = self.view.frame;
    [ self . view . layer insertSublayer : _preview atIndex : 0 ];
    
    //扫描区域框
    boxView = [[UIView alloc] initWithFrame:CGRectMake ((SCRE_WIDTH - 220)/ 2 , SCRE_HEIGHT/2-110 , 220 , 220 )];
    boxView.layer.borderColor = UIColorFromRGB(0x2CC32E).CGColor;
    boxView.layer.borderWidth = 1.0f;
    [self.view addSubview:boxView];
    
    //4个角
    UIImageView *imgb1 = [[UIImageView alloc]initWithFrame:CGRectMake(boxView.frame.origin.x-5, boxView.frame.origin.y-5, 17, 17)];
    imgb1.image = [UIImage imageNamed:@"b1"];
    [self.view addSubview:imgb1];
    
    UIImageView *imgb2 = [[UIImageView alloc]initWithFrame:CGRectMake(boxView.frame.origin.x+208, boxView.frame.origin.y-5, 17, 17)];
    imgb2.image = [UIImage imageNamed:@"b2"];
    [self.view addSubview:imgb2];
    
    UIImageView *imgb3 = [[UIImageView alloc]initWithFrame:CGRectMake(boxView.frame.origin.x-5, boxView.frame.origin.y+208, 17, 17)];
    imgb3.image = [UIImage imageNamed:@"b3"];
    [self.view addSubview:imgb3];
    
    UIImageView *imgb4 = [[UIImageView alloc]initWithFrame:CGRectMake(boxView.frame.origin.x+208, boxView.frame.origin.y+208, 17, 17)];
    imgb4.image = [UIImage imageNamed:@"b4"];
    [self.view addSubview:imgb4];
    
    //周围模糊背景
    CALayer *ca1 = [[CALayer alloc] init];
    ca1.frame = CGRectMake ((SCRE_WIDTH - 220)/ 2 ,64 , SCRE_WIDTH, boxView.frame.origin.y-64);
    ca1.backgroundColor = [UIColor blackColor].CGColor;
    ca1.opacity = 0.4;
    [self.view.layer addSublayer:ca1];
    
    CALayer *ca2 = [[CALayer alloc] init];
    ca2.frame = CGRectMake (0 ,64 , (SCRE_WIDTH - 220)/ 2, SCRE_HEIGHT-60+64);
    ca2.backgroundColor = [UIColor blackColor].CGColor;
    ca2.opacity = 0.4;
    [self.view.layer addSublayer:ca2];
    
    CALayer *ca3 = [[CALayer alloc] init];
    float w = SCRE_WIDTH - ((SCRE_WIDTH - 220)/ 2+220);
    ca3.frame = CGRectMake ((SCRE_WIDTH - 220)/ 2, boxView.frame.origin.y+220,SCRE_WIDTH-w*2,SCRE_HEIGHT-(60 + 64+220));
    ca3.backgroundColor = [UIColor blackColor].CGColor;
    ca3.opacity = 0.4;
    [self.view.layer addSublayer:ca3];
    
    CALayer *ca4 = [[CALayer alloc] init];
    ca4.frame = CGRectMake (SCRE_WIDTH-w,boxView.frame.origin.y,w,SCRE_HEIGHT-60+64);
    ca4.backgroundColor = [UIColor blackColor].CGColor;
    ca4.opacity = 0.4;
    [self.view.layer addSublayer:ca4];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    [timer fire];
    // Start
    [ _session startRunning ];
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    if (_session) {
        [self ref];
    }
}
-(void)ref{
    _scanLayer = [[UIImageView alloc] init];
    _scanLayer.frame = CGRectMake(-5, 0, boxView.bounds.size.width+10,5);
    
    _scanLayer.image = [UIImage imageNamed:@"line.png"];
    [boxView addSubview:_scanLayer];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    [timer fire];
    
    [_session startRunning];
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- ( void )captureOutput:( AVCaptureOutput *)captureOutput didOutputMetadataObjects:( NSArray *)metadataObjects fromConnection:( AVCaptureConnection *)connection
{
    NSLog(@"xhw扫描结果");
    NSString *stringValue;
    if ([metadataObjects count ] > 0 )
    {
        //停止扫描
        [ _session stopRunning ];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        stringValue = metadataObject. stringValue;
        NSLog(@"二维码结果%@",stringValue);
        [_scanLayer removeFromSuperview];
        NSArray *strings = [stringValue componentsSeparatedByString: @":"];
        
        NSMutableDictionary *dic =  [[NSMutableDictionary alloc]init];
        [dic setObject:[strings lastObject] forKey:@"sessionid"];
        [dic setObject:[AppDelegate shareDelegate].user.uid forKey:@"uids"];
        
        
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        GroupDetails *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupDetails"];
        NSLog(@"push");
        TCSession *session = [[TCSession alloc]init];
        session.ID = [strings lastObject] ;
        searchResultDetailController.session = session;
        searchResultDetailController.isqrcode = YES;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"延迟执行");
            [self ref];
        });
    }
}
//实现计时器方法moveScanLayer:(NSTimer *)timer

- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = _scanLayer.frame;
    if (boxView.frame.size.height-2 < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        frame.origin.y += 2;
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
